<?php

class getConfOsirideTask extends baseWemTask
{

    private $host;
    private $dbUser;
    private $dbPass;
    
    private $mysqli;
   
    private $samOsiride_ConfTab="tcnfab_obj_idf";
    private $samOsiride_ConfPwm="tcnf06_pwm";
    private $samOsiride_ConfPwmZon="tcnf20_gsezon";
    
    
    static public $samOsiride_DevType=array(
        "Energy Meter.GSE"=>"4",
        "Energy Meter.AUX"=>"28",
        "Energy Meter.Exchange"=>"27",
        "Energy Meter.GSESubPlant"=>"40",
        "Inverter.Centralizzato"=>"5",
        "Inverter.Unknown"=>"34",
        "Inverter.Stringa"=>"6",
        "String Comb.Unknown"=>"35",
        "String Comb"=>"24",
        "Weather"=>"22",
        "MV Protection.Interfaccia"=>"26"
    );
        
    static public $samOsiride_Select = array(
        "Conf"=>"T_GuiPath, N_Type, N_ServID",
    );
    

    static public $samOsiride_Var = array(
        "address2"=>"N_ServID",
        "address"=>"T_GuiPath",
        "type"=>"N_Type"
    );
    
    public function configure()
    {
        parent::configure();

        $this->name      = 'getConf-osiride';
        $this->briefDescription = 'Get Configuration Data from the Samares Osiride';

        $this->dbUser="root";
        $this->dbPass="sama012009";
        
        //OPTIONS
        $this->addOptions(array(
            new sfCommandOption('mode', null, sfCommandOption::PARAMETER_REQUIRED,'Execution mode: check already configured plant [update], or first configuration[new]', 'update'),   ));
        
        //ARGUMENTS
        $this->addArgument('plant',  sfCommandArgument::OPTIONAL,'Plant to check',0);
    }
    public function execute($arguments = array(), $options = array())
    {   
        //register log file
        $this->addFileLogger();
        
        //Get DB Connection
        $this->ConnectDB();
        
        //register task execution
        $tasklog=seth::regTaskStart($this->name, $arguments, $options );

        if ($arguments['plant']!=0){

           // $plants=new Plant();
            $plants=Doctrine_Core::getTable('plant')->findById($arguments['plant']);
            if (!is_object($plants)){
                $this->logBlock("The provided plant does not exist", "ERROR");
                seth::regTaskEnd($tasklog, false);
                die();
            }
        }       
        else{
            $plants=Doctrine_Core::getTable('Plant')->GetPlantIndex(array(
          "orderBy"=>"name",
          "indexOrder"=>"ASC"));
        }
        
        foreach ($plants as $plantTemp){
            
            $plantId=$plantTemp->getId();
            $plant=Doctrine_Core::getTable('plant')->find($plantId);
            $this->logBlock("Working on ".$plant->getName(), "INFO");
            //get Osiride ip adress
            $osiride=$plant->getNetDev(array("type"=>"Osiride"))->getFirst();
            
            if (is_object($osiride))
                $this->host=$osiride->getIp1();
            else{
                $this->logBlock("Osiride of ".$plant->getName()." not found","ERROR");
                break;
            }
                

            //check if Osiride is Up
            if ($osiride->isPingable()){
                $opt=array();
                if ($options['debug'])
                    array_push ($opt,"debug");
                $args=array('host'=> $this->host, "prot" => "ICMP", "iter" => 2);
                $hostIsUp=$this->runTask("wem:isUp", $args ,$opt);
                if (!$hostIsUp['isUp']){
                    $this->logBlock($plantName." Osiride @".$this->host." is DOWN.\n","ERROR");
                    seth::regTaskEnd($tasklog, false);
                    die();
                }
            }
            
            // set up a connection or die
            $this->mysqli = new mysqli($this->host, $this->dbUser, $this->dbPass, "osiride");
            if ($this->mysqli->connect_errno) {
                $this->logBlock("Failed to connect to MySQL: " . $this->mysqli->connect_error, "ERROR");
                break;
            }
            $this->logBlock("Connected as ".$this->dbUser." to MYSQL server @".$this->host, "INFO");

            $table=$this->samOsiride_ConfTab;
            $fields=implode(",",self::$samOsiride_Var); 
            $sql=" SELECT ".$fields." FROM ".$table;
            
            $result = $this->mysqli->query($sql);
            if ($result) {
                
                if ($result->num_rows>0){
                    
                    while ($row = $result->fetch_assoc()) {
                            
                            $plant=Doctrine_Core::getTable('plant')->find($plantId);
                            $type=array_search($row[self::$samOsiride_Var["type"]], self::$samOsiride_DevType);
                            if ($type){
                                
                                $subtype=NULL;
                                if (strpos($type,"."))
                                    list($type,$subtype)=explode(".",$type);

                                //check if the device already exist using address1       
                                $dev=$plant->getPowerDevBy(array(
                                        "type"=>$type,
                                        "address"=>$row[self::$samOsiride_Var["address"]] 
                                        ));

                                if ($dev){
                                    //device already registered with acqSyst1
                                    $addr2=$dev->getAddress2();

                                    if (!isset($addr2) or $addr2==""){
                                        //the device does not has acqSyst2 => register it!

                                        $dev->setSource2("SamOsiride");
                                        $dev->setAddress2($row[self::$samOsiride_Var["address2"]]);
                                        $dev->save();
                                        $this->logBlock("FOUND ".$type." ".$subtype." addr1: ".$row[self::$samOsiride_Var["address"]]." in ".$plant->getName().": inserted source2:SamOsiride and addr2: ".$row[self::$samOsiride_Var["address2"]], "INFO");

                                    }else
                                        $this->logBlock($type." ".$subtype." addr1: ".$row[self::$samOsiride_Var["address"]].",addr2: ".$row[self::$samOsiride_Var["address2"]]." already registered in ".$plant->getName(), "INFO");                
                                 
                                   //check the energy meter costant
                                    if ($type=="Energy Meter"){
                                        $k=$this->getMetMFactor($dev->getAddress2(), $subtype);
                                        if (isset($k))
                                            if ($k>1){
                                                $dev->setNote("K=".$k);
                                                $dev->save();
                                                $this->logBlock("\t Multiplication factor ".$k." configured for meter".$dev->getLabel(),"INFO");
                                            }

                                    }
                                    }else{
                                        //dev not registered!
                                        $this->logBlock($type." ".$subtype." ".$row[self::$samOsiride_Var["address"]].",addr2: ".$row[self::$samOsiride_Var["address2"]]." not found in ".$plant->getName(), "INFO");

                                        if ($options["mode"]=="new"){

                                            $newDev=new Powerdev();
                                            $newDev->setPlant($plant);
                                            $newDev->setType($type);
                                            $newDev->setSubtype(str_replace(array("SubPlant","Unknown"), "", $subtype));
                                            $newDev->setAddress($row[self::$samOsiride_Var["address"]]);
                                            $newDev->setSource("SamIoc");
                                            $newDev->setAddress2($row[self::$samOsiride_Var["address2"]]);
                                            $newDev->setSource2("SamOsiride");
                                            $newDev->setQuantity(1);

                                            $this->logBlock("\n \t Mode [new]: Inserting New PowerDev: Plant=".$plant.", Type=".$type.", SubType=".$newDev->getSubtype().", Address=".$newDev->getAddress().", Source=".$newDev->getSource().", Address2=".$newDev->getAddress2().", Source2=".$newDev->getSource2().", Quantity=1","INFO");

                                            $newDev->save();
                                            $newDev->free(true);
                                            unset($newDev);

                                        }
                                    }
                        }
                    }
                }else{
                    $this->logBlock(" MySQL returned an empty result set (i.e. zero rows). ","ERROR");
                    break;
                }
                $result->free();
            }else{
                $this->logBlock("\n Query Error ".$sql,"ERROR");
                break;
            } 
            
            $this->mysqli->close();
            unset($osiride);
            unset($result);
            
        }
        seth::regTaskEnd($tasklog, TRUE);        
    }
    private function getMetMFactor($id,$subtype){
        $table=  strpos($subtype, "SubPlant")!= FALSE ?"tcnf20_gsezon":"tcnf06_pwm";
        $fields="C_PwmID, N_MultFact"; 
        $sql=" SELECT ".$fields." FROM ".$table." WHERE C_PwmID=".$id." limit 0,1";

        $result = $this->mysqli->query($sql);
        if ($result) {
          if ($result->num_rows>0){
            while ($row = $result->fetch_assoc()) {
                  return $row["N_MultFact"];                                             
            }
          }
        }
        
        return NULL;
    }
    
}



?>

